package com.qs.user.ui.activity;

import android.annotation.SuppressLint;
import android.databinding.BindingAdapter;
import android.databinding.Observable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qs.base.base.BaseMyActivity;
import com.qs.base.router.RouterActivityPath;
import com.qs.base.utils.SystemUtil;
import com.qs.user.BR;
import com.qs.user.R;
import com.qs.user.databinding.UserMemberCenterActivityBinding;
import com.qs.user.pay.PayUtil;
import com.qs.user.pay.util.PayCallBack;
import com.qs.user.ui.VM.MemberCenterViewModel;
import com.qs.widget.widget.CommonPopupWindow;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * 会员中心
 *
 * @Author ltzz
 * @Date 2019/8/23
 */
@Route(path = RouterActivityPath.User.MEMBER_CENTER_ACTIVITY)
public class MemberCenterActivity extends BaseMyActivity<UserMemberCenterActivityBinding, MemberCenterViewModel> implements View.OnClickListener {

    private int popType = -1;

    @Override
    protected boolean statusBarDarkFont() {
        return true;
    }

    @Override
    protected View titleLayout() {
        return binding.head;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.user_member_center_activity;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel.clientId = SystemUtil.androidId(this);

    }


    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //登录
        viewModel.uc.login.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                initExportPop();
            }
        });
        //15元会员点击
        viewModel.uc.member1Uc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                viewModel.money = Float.parseFloat(viewModel.money1.get());
                viewModel.buttonStr.set("支付¥" + viewModel.money1.get());
                binding.member1.setVisibility(View.VISIBLE);
                binding.member3.setVisibility(View.INVISIBLE);
                binding.member12.setVisibility(View.INVISIBLE);
            }
        });
        //3月会员点击
        viewModel.uc.member3Uc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                viewModel.money = Float.parseFloat(viewModel.money3.get());
                viewModel.buttonStr.set("支付¥" + viewModel.money3.get());
                binding.member1.setVisibility(View.INVISIBLE);
                binding.member3.setVisibility(View.VISIBLE);
                binding.member12.setVisibility(View.INVISIBLE);
            }
        });
        //12月会员点击
        viewModel.uc.member12Uc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                viewModel.money = Float.parseFloat(viewModel.money12.get());
                viewModel.buttonStr.set("支付¥" + viewModel.money12.get());
                binding.member1.setVisibility(View.INVISIBLE);
                binding.member3.setVisibility(View.INVISIBLE);
                binding.member12.setVisibility(View.VISIBLE);
            }
        });
        //确认支付
        viewModel.uc.paymentUc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (StringUtils.isTrimEmpty(viewModel.userId)) {
                    ToastUtils.showShort("请先登录！");
                    return;
                }
                initPayPop();
            }
        });
        //支付宝支付
        viewModel.uc.aliPayUc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                ToastUtils.showLong("正在拉起支付宝...");
                PayUtil.doAliPay(viewModel.uc.aliPayUc.get(), MemberCenterActivity.this, new PayCallBack() {
                    @Override
                    public void onSuccess() {
                        dismissDialog();
                        viewModel.addNumbers(viewModel.userId, viewModel.month * 60000 + "");
                        viewModel.getVIPInfo(viewModel.userId);
                    }
                });
            }
        });
        //微信支付
        viewModel.uc.wxPayUc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                ToastUtils.showLong("正在拉起微信...");
                PayUtil.doWXPay(viewModel.uc.wxPayUc.get(), MemberCenterActivity.this, new PayCallBack() {
                    @Override
                    public void onSuccess() {
                        dismissDialog();
                        viewModel.addNumbers(viewModel.userId, viewModel.month * 60000 + "");
                        viewModel.getVIPInfo(viewModel.userId);
                    }
                });
            }
        });
    }

    CommonPopupWindow loginPop;

    //登录弹窗
    @SuppressLint("NewApi")
    private void initExportPop() {
        popType = 0;
        View photoView = LayoutInflater.from(this).inflate(R.layout.user_pop_login, null);
        TextView qqStr = photoView.findViewById(R.id.alipay_name);//qq
        qqStr.setText("QQ");
        TextView hint = photoView.findViewById(R.id.hint);
        hint.setText("请选择登录方式");
        ImageView qqImg = photoView.findViewById(R.id.alipay);//qq登录
        qqImg.setImageResource(R.drawable.user_qq_icon);
        qqImg.setOnClickListener(this);//qq登录
        photoView.findViewById(R.id.wechat).setOnClickListener(this);//微信登录
        loginPop = new CommonPopupWindow.Builder(this)
                //设置PopupWindow布局
                .setView(photoView)
                //设置宽高
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT)
                //设置动画
//                .setAnimationStyle(R.style.base_AnimDown)
                //设置背景颜色，取值范围0.0f-1.0f 值越小越暗 1.0f为透明
                .setBackGroundLevel(0.3f)
                //设置PopupWindow里的子View及点击事件
                .setViewOnclickListener(new CommonPopupWindow.ViewInterface() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                    }
                })
                //设置外部是否可点击 默认是true
                .setOutsideTouchable(true)
                //开始构建
                .create();
        loginPop.showAtLocation(binding.popOut, Gravity.CENTER, 0, 0);
    }

    //支付弹窗
    @SuppressLint("NewApi")
    private void initPayPop() {
        popType = 1;
        View photoView = LayoutInflater.from(this).inflate(R.layout.user_pop_login, null);
        ImageView qqImg = photoView.findViewById(R.id.alipay);//支付宝支付
        qqImg.setImageResource(R.drawable.user_alipay_ico);
        qqImg.setOnClickListener(this);//支付宝支付
        photoView.findViewById(R.id.wechat).setOnClickListener(this);//微信支付
        loginPop = new CommonPopupWindow.Builder(this)
                //设置PopupWindow布局
                .setView(photoView)
                //设置宽高
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT)
                //设置动画
//                .setAnimationStyle(R.style.base_AnimDown)
                //设置背景颜色，取值范围0.0f-1.0f 值越小越暗 1.0f为透明
                .setBackGroundLevel(0.3f)
                //设置PopupWindow里的子View及点击事件
                .setViewOnclickListener(new CommonPopupWindow.ViewInterface() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                    }
                })
                //设置外部是否可点击 默认是true
                .setOutsideTouchable(true)
                //开始构建
                .create();
        loginPop.showAtLocation(binding.popOut, Gravity.CENTER, 0, 0);
    }


    /**
     * 微信授权登录
     */
    public void wxLogin() {
        cn.sharesdk.framework.Platform plat = ShareSDK.getPlatform(Wechat.NAME);
        if (plat.isAuthValid())
            plat.removeAccount(true);
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                ToastUtils.showShort("Error");
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                KLog.e(arg0.getDb().exportData());
                viewModel.register(arg0.getDb().getUserIcon(), arg0.getDb().getUserId(), "", arg0.getDb().getUserName());
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                ToastUtils.showShort("取消");
            }
        });
        String userId = plat.getDb().getUserId();
        KLog.e(userId);
        //        plat.authorize();//授权不返回用户信息
        plat.showUser(null);//授权返回用户信息
    }

    /**
     * qq授权登录
     */
    public void txLogin() {
        Platform plat = ShareSDK.getPlatform(cn.sharesdk.tencent.qq.QQ.NAME);
        if (plat.isAuthValid())
            plat.removeAccount(true);
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
                ToastUtils.showShort("Error");
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                //输出所有授权信息
                KLog.e(arg0.getDb().exportData());
                viewModel.register(arg0.getDb().getUserIcon(), arg0.getDb().getUserId(), "", arg0.getDb().getUserName());
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub
                ToastUtils.showShort("取消");
            }
        });
        String userId = plat.getDb().getUserId();
        KLog.e(userId);
        //        plat.authorize();//授权不返回用户信息
        plat.showUser(null);//授权返回用户信息
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.alipay) {
            loginPop.dismiss();
            if (popType == 0)
                txLogin();//qq登录
            if (popType == 1) {
                //支付宝支付
                viewModel.creatOrder("支付宝官方支付");
            }
        }
        if (id == R.id.wechat) {
            loginPop.dismiss();
            if (popType == 0)
                wxLogin();//微信登录
            if (popType == 1) {
                //微信支付
                viewModel.creatOrder("微信官方支付");
            }
        }
    }

    @BindingAdapter({"imageUrl"})
    public static void loadImage(ImageView imageView, String url) {
        RequestOptions mRequestOptions = new RequestOptions()
                .override(imageView.getWidth(), imageView.getHeight())
                .error(R.drawable.user_member_user);
        Glide.with(imageView.getContext())
                .load(url)
                .apply(mRequestOptions)
                .into(imageView);
    }

}
